from fastapi import APIRouter, Depends, Form, Request, Query, HTTPException
from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
from sqlalchemy.orm import Session
from typing import Optional
from pydantic import BaseModel
from ..models import get_db, Tag, User, WebsiteConfig
from ..auth import get_current_user
from ..utils import paginate_query
import os
from fastapi.templating import Jinja2Templates

# 状态切换请求模型
class ToggleStatusRequest(BaseModel):
    new_status: bool

router = APIRouter()

# 获取模板目录
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
templates = Jinja2Templates(directory=os.path.join(BASE_DIR, "templates"))

# 标签列表页面
@router.get("/tags", response_class=HTMLResponse)
async def admin_tags(
    request: Request, 
    page: int = Query(1, ge=1), 
    db: Session = Depends(get_db), 
    current_user: User = Depends(get_current_user)
):
    query = db.query(Tag).order_by(Tag.id)
    pagination = paginate_query(query, page, 20)
    
    # 获取网站配置
    config = db.query(WebsiteConfig).first()
    if not config:
        config = WebsiteConfig(background_effect="gradient")
    
    return templates.TemplateResponse("admin/tags.html", {
        "request": request, 
        "tags": pagination["items"],
        "current_page": pagination["current_page"],
        "total_pages": pagination["total_pages"],
        "total_items": pagination["total_items"],
        "page_size": pagination["page_size"],
        "current_user": current_user,
        "config": config
    })

# 添加标签页面
@router.get("/tags/add", response_class=HTMLResponse)
async def admin_add_tag(
    request: Request, 
    db: Session = Depends(get_db), 
    current_user: User = Depends(get_current_user)
):
    # 获取网站配置
    config = db.query(WebsiteConfig).first()
    if not config:
        config = WebsiteConfig(background_effect="stars")
    return templates.TemplateResponse(
        "admin/tag-form.html", 
        {"request": request, "action": "add", "current_user": current_user, "config": config}
    )

# 编辑标签页面
@router.get("/tags/edit/{tag_id}", response_class=HTMLResponse)
async def admin_edit_tag(
    request: Request, 
    tag_id: int, 
    db: Session = Depends(get_db), 
    current_user: User = Depends(get_current_user)
):
    tag = db.query(Tag).filter(Tag.id == tag_id).first()
    if not tag:
        raise HTTPException(status_code=404, detail="标签不存在")
    # 获取网站配置
    config = db.query(WebsiteConfig).first()
    if not config:
        config = WebsiteConfig(background_effect="stars")
    return templates.TemplateResponse(
        "admin/tag-form.html", 
        {"request": request, "tag": tag, "action": "edit", "current_user": current_user, "config": config}
    )

# 保存标签
@router.post("/tags/save")
async def save_tag(
    id: Optional[int] = Form(None),
    name: str = Form(...),
    is_active: bool = Form(False),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    if id:
        tag = db.query(Tag).filter(Tag.id == id).first()
        if not tag:
            raise HTTPException(status_code=404, detail="标签不存在")
        tag.name = name
        tag.status = is_active
    else:
        tag = Tag(
            name=name,
            status=is_active
        )
        db.add(tag)
    db.commit()
    return RedirectResponse(url="/admin/tags", status_code=302)

# 删除标签
@router.post("/tags/delete/{tag_id}")
async def delete_tag(
    tag_id: int,
    request: Request,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    tag = db.query(Tag).filter(Tag.id == tag_id).first()
    if not tag:
        # 检查是否是异步请求
        is_ajax = request.headers.get("X-Requested-With") == "XMLHttpRequest"
        if is_ajax:
            return {"success": False, "message": "标签不存在"}
        else:
            raise HTTPException(status_code=404, detail="标签不存在")
    
    # 检查是否是异步请求
    is_ajax = request.headers.get("X-Requested-With") == "XMLHttpRequest"
    
    db.delete(tag)
    db.commit()
    
    if is_ajax:
        # 对于异步请求，返回JSON响应
        return {"success": True, "message": "删除成功"}
    else:
        # 对于普通请求，返回重定向
        return RedirectResponse(url="/admin/tags?message=删除成功", status_code=302)

# 批量删除标签
@router.post("/tags/batch-delete")
async def batch_delete_tags(
    request: Request,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    form_data = await request.form()
    tag_ids = form_data.getlist("tag_ids")
    
    # 检查是否是异步请求
    is_ajax = request.headers.get("X-Requested-With") == "XMLHttpRequest"
    
    if tag_ids:
        # 将字符串ID列表转换为整数列表
        tag_ids = [int(id) for id in tag_ids]
        # 批量删除选中的标签
        db.query(Tag).filter(Tag.id.in_(tag_ids)).delete(synchronize_session=False)
        db.commit()
        
        if is_ajax:
            # 对于异步请求，返回JSON响应
            return {"success": True, "message": "批量删除成功"}
        else:
            # 对于普通请求，返回重定向
            return RedirectResponse(url="/admin/tags?message=批量删除成功", status_code=302)
    else:
        if is_ajax:
            # 对于异步请求，返回JSON响应
            return {"success": False, "message": "请选择要删除的标签"}
        else:
            # 对于普通请求，返回重定向
            return RedirectResponse(url="/admin/tags?message=请选择要删除的标签", status_code=302)

# 切换标签状态
@router.post("/tags/toggle-status/{tag_id}")
async def toggle_tag_status(
    tag_id: int,
    request_data: ToggleStatusRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    try:
        # 查找标签
        tag = db.query(Tag).filter(Tag.id == tag_id).first()
        
        if not tag:
            return JSONResponse(
                content={"success": False, "message": "标签不存在"},
                status_code=404
            )
        
        # 更新状态（这里应该是取反当前状态，而不是直接使用new_status）
        tag.status = not tag.status
        db.commit()
        
        status_text = "启用" if tag.status else "禁用"
        return JSONResponse(
            content={"success": True, "message": f"标签{status_text}成功", "new_status": tag.status}
        )
    except Exception as e:
        db.rollback()
        return JSONResponse(
            content={"success": False, "message": f"状态切换失败: {str(e)}"},
            status_code=500
        )